import 'package:filelinker/file_model.dart';
import 'package:filelinker/mdsn.dart';
import 'package:filelinker/netsev.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:nsd/nsd.dart';

class SendTextPopup extends StatefulWidget {
  const SendTextPopup({super.key, required this.device});

  final Service device;

  @override
  State<SendTextPopup> createState() => _SendTextPopupState();
}

class _SendTextPopupState extends State<SendTextPopup> {
  late TextEditingController _controller;
  double _bottom = 0;
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    if (MDNS.shared.isDesktop) {
      return;
    }
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _renewalKeyboardHeight();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    EasyLoading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (MDNS.shared.isDesktop) {
      return Center(
        child: _wContentView(),
      );
    }
    if (_bottom == 0) {
      _bottom = MediaQuery.of(context).size.height * 0.4;
    }
    return Stack(
      children: [
        AnimatedPositioned(
          right: 0,
          bottom: _bottom,
          left: 0,
          duration: const Duration(milliseconds: 200),
          child: _wContentView(),
        ),
      ],
    );
  }

  Widget _wContentView() {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.onPrimary,
      ),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            margin: const EdgeInsets.only(top: 10, left: 10),
            child: Text(
              "发送文本给${widget.device.xname()}：",
            ),
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  margin: const EdgeInsets.fromLTRB(10, 0, 0, 10),
                  child: TextField(
                    controller: _controller,
                    focusNode: _focusNode,
                  ),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.send),
                onPressed: _didTapSend,
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _renewalKeyboardHeight() {
    if (MDNS.shared.isDesktop) {
      return;
    }
    Future.delayed(const Duration(milliseconds: 400), () {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        _bottom = MediaQuery.of(context).viewInsets.bottom;
        debugPrint("bottom: $_bottom");
        setState(() {});
      });
    });
  }

  void _pop() {
    Navigator.of(context).pop();
  }

  void _didTapSend() async {
    final text = _controller.text;
    if (text.isEmpty) {
      EasyLoading.showToast("文本不能为空");
      return;
    }
    bool state = await _lookupAddress(text);
    if (state) {
      EasyLoading.showToast("发送成功");
      _pop();
    } else {
      EasyLoading.showToast("发送失败，请重试");
    }
  }

  Future<bool> _sendText(String? address, String text) async {
    if (address == null) return false;
    EasyLoading.show(status: "发送中...");
    debugPrint('address: $address');
    var state = await NetService.shared.sendText(
      address,
      widget.device.port,
      text,
      MDNS.shared.name,
    );
    EasyLoading.dismiss();
    return state;
  }

  Future<bool> _lookupAddress(String text) async {
    if (await _sendText(widget.device.host, text)) {
      return true;
    }
    bool isDone = false;
    if (widget.device.addresses != null) {
      for (var addr in widget.device.addresses!) {
        if (await _sendText(addr.address, text)) {
          isDone = true;
          break;
        }
      }
    }
    return isDone;
  }
}
